using Autodesk.Revit.Attributes;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using CodRevit.ViewModels;
using CodRevit.Views;
using CodRevit.Services;
using System;
using System.Linq;

namespace CodRevit.Commands
{
    /// <summary>
    /// 模拟选择命令
    /// 模拟选择当前视图中的所有元素，默认每个元素展示2秒
    /// </summary>
    [Transaction(TransactionMode.Manual)]
    public class SimulateSelectCommand : IExternalCommand
    {
        public Result Execute(ExternalCommandData commandData, ref string message, ElementSet elements)
        {
            try
            {
                UIApplication uiapp = commandData.Application;
                UIDocument uidoc = uiapp.ActiveUIDocument;
                Document doc = uidoc.Document;

                // 创建服务实例
                var simulateSelectService = new SimulateSelectService();

                // 获取当前视图中的所有可选择元素
                var selectableElements = simulateSelectService.GetSelectableElements(doc, uidoc.ActiveView);
                
                if (!selectableElements.Any())
                {
                    TaskDialog.Show("提示", "当前视图中没有找到可选择的元素。");
                    return Result.Succeeded;
                }

                // 创建窗口和ViewModel，注入服务
                var window = new SimulateSelectView();
                var viewModel = new SimulateSelectViewModel(simulateSelectService, uidoc, selectableElements);
                window.DataContext = viewModel;

                // 显示模态窗口
                var result = window.ShowDialog();
                
                // 注意：不要在这里释放服务，因为模拟选择可能还在异步执行
                // 服务会在模拟完成后自动清理资源

                return Result.Succeeded;
            }
            catch (Exception ex)
            {
                TaskDialog.Show("错误", $"执行命令时发生错误：{ex.Message}");
                return Result.Failed;
            }
        }
    }
}